package com.example.student_management.exception;

import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理@RequestParam参数验证失败
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleConstraintViolationException(ConstraintViolationException e) {
        Map<String, String> errors = new HashMap<>();
        // 遍历所有验证失败的信息
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            // 获取参数名（如"getUser.id"中的"id"）
            String paramName = violation.getPropertyPath().toString().split("\\.")[1];
            errors.put(paramName, violation.getMessage());
        }
        return errors;
    }
}
